<template>
  <view class="ai-chat-container">
    <!-- 标题区域 -->
    <view class="header">
      <text class="title">我是您的就医智能助手</text>
      <text class="subtitle">专业、可靠，随时为您解答就医相关问题</text>
    </view>
    
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-into-view="scrollToId"
      :enable-back-to-top="true"
    >
    
    <!-- 操作提示 -->
    <view class="suggestions">
      <text class="suggestion-title">您可以问：</text>
      <view class="suggestion-list">
        <view 
          v-for="(suggestion, idx) in quickSuggestions" 
          :key="idx"
          class="suggestion-item"
          @tap="selectSuggestion(suggestion)"
        >
          <text>{{ suggestion }}</text>
        </view>
      </view>
    </view>
    
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        :id="'msg' + index"
        :class="['message', msg.role]"
      >   
      
        <!-- AI消息 -->
        <view v-if="msg.role === 'assistant'" class="message-content">
          <!-- <view class="avatar">
            <image src="/static/logo.png" mode="aspectFit"></image>
          </view> -->
          <view class="text-bubble ai-bubble">
            <text class="text-content">{{ msg.content }}</text>
            <view v-if="index === messages.length - 1 && isTyping" class="typing-indicator">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
        
        <!-- 用户消息 -->
        <view v-else class="message-content user-message">
          <view class="text-bubble user-bubble">
            <text class="text-content">{{ msg.content }}</text>
          </view>
          <view class="avatar">
            <image src="/static/img/我的.png" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <input 
        class="chat-input" 
        v-model="inputMessage"
        placeholder="输入您的问题..."
        placeholder-style="color: #9E9E9E;"
        :adjust-position="false"
        :focus="autoFocus"
        confirm-type="send"
        @confirm="sendMessage"
        @input="adjustInput"
      />
      <button 
        class="send-button" 
        :disabled="isLoading" 
        @tap="sendMessage"
      >
        <text v-if="!isLoading">发送</text>
        <view v-else class="loading-spinner">
          <view class="spinner"></view>
        </view>
      </button>
    </view>    
    
  </view>
</template>

<script>
// 注意：实际使用时，需要将API密钥放在安全的地方（如云函数中）
// 此处仅为演示，请勿在前端直接暴露API密钥
const DEEPSEEK_API_KEY = "sk-eebb91e05b13449884b5419172614a2c"; // 您的DeepSeek API Key
const API_URL = "https://api.deepseek.com/chat/completions";

export default {
  data() {
    return {
      messages: [
        {
          role: "assistant",
          content: "您好！我是您的就医智能助手。可以为您解答关于医院科室、挂号流程、诊疗建议等方面的问题。请问有什么可以帮您的吗？"
        }
      ],
      inputMessage: "",
      isLoading: false,
      isTyping: false,
      autoFocus: false,
      scrollToId: ""
    };
  },
  computed: {
    quickSuggestions() {
      return [
        "如何预约挂号？",
        "北京协和医院有什么特色科室？",
        "胃痛应该挂什么科？",
        "住院需要准备什么材料？"
      ];
    }
  },
  methods: {
    // 发送消息到DeepSeek API
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return;
      
      // 添加用户消息
      const userMessage = this.inputMessage.trim();
      this.messages.push({ role: "user", content: userMessage });
      this.inputMessage = "";
      this.autoFocus = false;
      
      // 模拟发送状态
      this.isLoading = true;
      this.isTyping = true;
      this.scrollToLastMessage();
      
      try {
        // 组织对话历史（保留最近的3条对话）
        const messagesToSend = [
          { role: "system", content: "你是一个专业的医疗就医助手，提供就医相关的帮助和建议。" }, // 增加系统角色设定
          ...this.messages.slice(Math.max(this.messages.length - 5, 0)),
        ];
        
        // 使用uni.request发送请求（微信小程序环境）
        const response = await new Promise((resolve, reject) => {
          uni.request({
            url: API_URL,
            method: "POST",
            header: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${DEEPSEEK_API_KEY}`
            },
            data: {
              model: "deepseek-chat",
              messages: messagesToSend,
              stream: false, // 简化处理，不使用流式返回
              max_tokens: 1000
            },
            success: (res) => {
              if (res.statusCode >= 200 && res.statusCode < 300) {
                resolve(res.data);
              } else {
                reject(new Error(`API请求失败: ${res.statusCode}`));
              }
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
        
        // 处理响应
        if (response && response.choices && response.choices.length > 0) {
          const aiReply = response.choices[0].message.content;
          this.messages.push({ role: "assistant", content: aiReply });
        } else {
          this.messages.push({
            role: "assistant",
            content: "抱歉，我暂时无法回答这个问题。请尝试换一种问法或描述更具体一些。"
          });
        }
      } catch (error) {
        console.error("API调用错误:", error);
        this.messages.push({
          role: "assistant",
          content: "抱歉，我遇到了一些问题。请稍后再试或联系我们的客服人员。"
        });
      } finally {
        this.isLoading = false;
        this.isTyping = false;
        this.scrollToLastMessage();
      }
    },
    
    // 选择快速建议
    selectSuggestion(suggestion) {
      this.inputMessage = suggestion;
      this.autoFocus = true;
    },
    
    // 滚动到最新消息
    scrollToLastMessage() {
      this.$nextTick(() => {
        const lastIndex = this.messages.length - 1;
        this.scrollToId = `msg${lastIndex}`;
      });
    },
    
    // 调整输入框位置（处理键盘弹出）
    adjustInput() {
      this.scrollToLastMessage();
    }
  }
};
</script>

<style scoped>
/* 主容器 */
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f9fb;
  padding: 20rpx;
  box-sizing: border-box;
}

/* 头部区域 */
.header {
  text-align: center;
  margin-bottom: 30rpx;
  padding-top: 20rpx;
}

.title {
  font-size: 38rpx;
  font-weight: bold;
  color: #2c3e50;
  display: block;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 26rpx;
  color: #7f8c8d;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
}

.suggestions {
  margin-bottom: 20rpx;
  padding: 10rpx 20rpx;
  background-color: #eaf3ff;
  border-radius: 12rpx;
}

.suggestion-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.suggestion-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.suggestion-item {
  background-color: #ffffff;
  border: 1px solid #dcdcdc;
  border-radius: 25rpx;
  padding: 12rpx 25rpx;
  font-size: 26rpx;
  color: #555;
  cursor: pointer;
  transition: all 0.2s ease;
}

.suggestion-item:active {
  background-color: #f0f0f0;
  transform: translateY(1rpx);
}

.message {
  display: flex;
  margin-bottom: 25rpx;
}

.message-content {
  display: flex;
  align-items: flex-start;
  max-width: 80%;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 15rpx;
  flex-shrink: 0;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.text-bubble {
  padding: 20rpx 28rpx;
  border-radius: 18rpx;
  font-size: 30rpx;
  line-height: 1.6;
  word-break: break-word;
  position: relative;
}

.ai-bubble {
  background-color: #e0f2fe;
  color: #333;
  border-bottom-left-radius: 0;
}

.user-bubble {
  background-color: #1e90ff;
  color: white;
  border-bottom-right-radius: 0;
}

/* 输入区域 */
.input-area {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #e0e0e0;
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
}

.chat-input {
  flex: 1;
  height: 80rpx;
  padding: 0 30rpx;
  background-color: #f0f0f0;
  border-radius: 40rpx;
  font-size: 30rpx;
  margin-right: 20rpx;
  color: #333;
}

.send-button {
  width: 120rpx;
  height: 80rpx;
  background-color: #1E90FF;
  color: white;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
  padding: 0;
  line-height: 1; /* 确保文本垂直居中 */
}

.send-button[disabled] {
  background-color: #a5ccf7;
  color: #e0e0e0;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.spinner {
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top: 4rpx solid #fff;
  border-radius: 50%;
  width: 30rpx;
  height: 30rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.typing-indicator {
  display: flex;
  align-items: center;
  height: 20rpx; /* 确保点点动画在气泡内 */
  margin-top: 10rpx;
}

.dot {
  width: 8rpx;
  height: 8rpx;
  background-color: #333;
  border-radius: 50%;
  margin: 0 4rpx;
  animation: blink 1.4s infinite both;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes blink {
  0% { opacity: 0.2; }
  20% { opacity: 1; }
  100% { opacity: 0.2; }
}
</style> 